package cn.jobstart.controller;

import cn.jobstart.common.StringUtil;
import cn.jobstart.es.dto.ResumeEsPageDTO;
import cn.jobstart.es.model.ResumeEs;
import cn.jobstart.es.search.ResumeEsSearch;
import cn.jobstart.es.service.IResumeEsService;
import cn.jobstart.es.vo.ResumeEsDetailVO;
import cn.jobstart.es.vo.ResumeEsListVO;
import cn.jobstart.es.vo.ResumeEsVO;
import cn.jobstart.model.AdminJobCandidate;
import cn.jobstart.modelExt.AdminJobCandidateExt;
import cn.jobstart.pubInter.IBaseService;
import cn.jobstart.pubInter.common.PageBean;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.service.IAdminJobCandidateService;
import cn.jobstart.service.IResumeBasicService;
import cn.jobstart.vo.AdminJobCandidateDomainVO;
import cn.jobstart.web.common.SkJsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sunke
 * @version 1.0
 * @Description
 * @date 2023-09-06 17:33
 */
@RestController
@RequestMapping("/es/")
@Api(tags = "人才管理系统-简历搜索", description = "简历搜索接口")
public class EsController extends ApiManageController {


    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private IResumeBasicService resumeBasicService;
    @Resource
    private IResumeEsService resumeEsService;
    @Resource
    private IAdminJobCandidateService adminJobCandidateService;

    @Override
    public IBaseService getBaseService() throws SkException {
        return null;
    }

    @ApiOperation(value = "详情", notes = "详情", httpMethod = "POST")
    @PostMapping({"detailInfo/{id}"})
    public SkJsonResult<ResumeEsVO> detailInfo(@PathVariable("id") String id, HttpServletRequest request, HttpSession session) throws SkException {
        return SkJsonResult.ok().setData(map(resumeEsService.detailById(id),ResumeEsVO.class));
    }





    /*    @GetMapping("/createIndex")
    public Boolean createIndex() throws SkException {
        // 1.初始化-> 创建索引(相当于mysql中的表)
        return resumeEsService.createIndex();
    }*/


/*    @GetMapping("/deleteIndex")
    public Boolean deleteIndex() throws SkException {
        return resumeEsService.deleteIndex();
    }*/



/*    @GetMapping("/insert/{resumeId}")
    public Integer insert(@PathVariable String resumeId) throws SkException {


        ResumeBasicExt resumeBasic = resumeBasicService.getDetail(resumeId);
        ResumeEs resumeEs = new ResumeEs();
        BeanUtils.copyProperties(resumeBasic, resumeEs);

        return resumeEsService.insert(resumeEs);

    }*/

   /* @GetMapping("/publish/{resumeId}")
    public Integer publish(@PathVariable String resumeId) throws SkException {

        ResumeBasicSearchExt search = ResumeBasicSearchExt.getInstance();
        int pageNum = 1;
        while (true) {
            search.setPageNumber(pageNum);
            DecoratePageList<ResumeBasicExt> page = resumeBasicService.paginateToObject(search);

            if (StringUtil.isNullOrEmpty(page) || StringUtil.isNullOrEmpty(page.getList())) {
                break;
            }
            page.getList().stream().forEach(item -> {

                try {
                    resumeEsService.publishByResumeId(item.getId());
                } catch (SkException e) {

                }


            });

            pageNum = pageNum + 1;


        }


        // resumeEsService.publishByResumeId(resumeId);

        return 0;

    }*/

    @Override
    public String getBaseRoute() throws SkException {
        return null;
    }

    @ApiOperation(value = "简历搜索", notes = "简历搜索")
    @PostMapping("esList")
    public SkJsonResult<ResumeEsListVO> esList(@RequestBody ResumeEsPageDTO dto) throws SkException {

        ResumeEsSearch search = ResumeEsSearch.getInstance();
        cn.jobstart.common.BeanUtils.copyPropertiesIgnoreNull(dto, search);

        if (StringUtil.isNullOrEmpty(search.getOrderByDesc())) {

            search.sortByScore(SortOrder.DESC);
            search.orderByDesc(ResumeEs::getResumeModifyTime, ResumeEs::getResumeCreateTime);
        } else {
            search.orderByDesc(search.getOrderByDesc().stream().collect(Collectors.joining(",")));
        }


        //  search.minScore(10f);


        EsPageInfo<ResumeEs> pageInfo = resumeEsService.pageQuery(search, dto.getPageNumber(), dto.getPageSize());

        if (StringUtil.isNullOrEmpty(pageInfo) || StringUtil.isNullOrEmpty(pageInfo.getList())) {
            return SkJsonResult.ok();
        }

        PageBean page = new PageBean();

        page.setTotalCount(pageInfo.getTotal());
        page.setPageSize(dto.getPageSize());

        long totalPage = page.getTotalPage();
        long pageNumber = dto.getPageNumber();
        if (pageNumber > totalPage) {
            pageNumber = totalPage;
        }
        page.setCurrentPage(pageNumber);


        ResumeEsListVO vo = new ResumeEsListVO();

        EsPageInfo<ResumeEsDetailVO> result = new EsPageInfo<>();
        map(pageInfo, result);


        vo.setList(mapList(pageInfo.getList(), ResumeEsDetailVO.class));
        fullCandidateList(vo.getList());
        vo.setPage(page);


        return SkJsonResult.ok().setData(vo);

    }

    private void fullCandidateList(List<ResumeEsDetailVO> resumeList) {

        try {
            if (StringUtil.isNullOrEmpty(resumeList)) {
                return;
            }

            List<String> resumeIds = resumeList.stream().map(ResumeEsDetailVO::getId).distinct().collect(Collectors.toList());
            List<AdminJobCandidateExt> candidateList = adminJobCandidateService.getAllByInField(resumeIds, AdminJobCandidate.RESUME_ID, new HashSet<>());
            if (StringUtil.isNullOrEmpty(candidateList)) {
                return;
            }
            Map<String, List<AdminJobCandidateExt>> dataMap = candidateList.stream().collect(Collectors.groupingBy(AdminJobCandidateExt::getResumeId));
            resumeList.stream().forEach(item -> {
                try {
                    List<AdminJobCandidateDomainVO> oneCandidateList = mapList(dataMap.get(item.getId()), AdminJobCandidateDomainVO.class);
                    if (StringUtil.isNullOrEmpty(oneCandidateList) || oneCandidateList.size() < 5) {
                        item.setCandidateList(oneCandidateList);
                    } else {
                        item.setCandidateList(oneCandidateList.subList(0, 5));
                    }


                } catch (Exception e) {

                }


            });


        } catch (SkException e) {

        }


    }


}
